﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace MRSite.DataAccess.Config
{
    internal static class ConfigHelper
    {
        private const string NODE_NAME = "dataAccess";
        private const string DEFAULT_DATABASE_LIST_FILE_PATH = "Configs/Data/Database.config";

        private static string s_ConfigFolder = null;
        private static DataAccessInfo s_Setting = ConfigurationManager.GetSection(NODE_NAME) as DataAccessInfo;

        public static string DatabaseListFilePath
        {
            get
            {
                string path = s_Setting == null ? null : s_Setting.DatabaseListFile;
                if (path == null || path.Trim().Length <= 0)
                {
                    path = DEFAULT_DATABASE_LIST_FILE_PATH;
                }
                string p = Path.GetPathRoot(path);
                if (p == null || p.Trim().Length <= 0) // 说明是相对路径
                {
                    return Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, path);
                }
                return path;
            }
        }

        public static DatabaseList LoadDatabaseListFile()
        {
            return LoadFromXml<DatabaseList>(DatabaseListFilePath);
        }

        private static T LoadFromXml<T>(string fileName)
        {
            FileStream fs = null;
            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                return (T)serializer.Deserialize(fs);
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
            }
        }
    }
}
